﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIRootEx : UIRoot
{
    public bool isMainRoot;
    public Camera camera;

    protected override void Awake()
    {
        base.Awake();

        // this.manualHeight = Screen.height;
        // this.manualWidth = Screen.width;
    }

    [ContextMenu("RefreshScale")]
    public void RefreshScale ()
    {
        this.UpdateScale(true);
    }

    public override void UpdateScale (bool updateAnchors = true)
    {
        if (mTrans != null)
        {
            float scale = 1;
            if (camera != null)
            {
                if (camera.orthographic)
                {
                    scale = camera.orthographicSize;
                }
                else
                {
                    float tan = Mathf.Tan(Mathf.Deg2Rad * camera.fieldOfView / 2);
                    scale = (camera.transform.position - this.transform.position).magnitude * tan;
                }
            }

            float calcActiveHeight = activeHeight;

            if (calcActiveHeight > 0f)
            {
                float size = scale * 2f / calcActiveHeight;

                Vector3 ls = mTrans.localScale;

                if (!(Mathf.Abs(ls.x - size) <= float.Epsilon) ||
                    !(Mathf.Abs(ls.y - size) <= float.Epsilon) ||
                    !(Mathf.Abs(ls.z - size) <= float.Epsilon))
                {
                    mTrans.localScale = new Vector3(size, size, size);
                    if (updateAnchors) BroadcastMessage("UpdateAnchors", SendMessageOptions.DontRequireReceiver);
                }
            }
        }
    }
}
